<template>
  <div class="grid-selector">
    <div class="grid-container" @mouseleave="handleMouseLeave">
      <div v-for="row in 4" :key="row" class="grid-row">
        <div v-for="col in 4" :key="col" class="grid-cell" :class="{
          'hovered': isHovered(row, col),
          'selected': isSelected(row, col)
        }" @mouseover="handleMouseOver(row, col)" @click="handleClick(row, col)"></div>
      </div>
    </div>
    <div class="selection-info">
      已选择：{{ selectedRows }} 行 × {{ selectedCols }} 列
    </div>
  </div>
</template>

<script>
export default {
  name: 'GridSelector',
  props: {
    initialRows: {
      type: Number,
      default: 1 // 默认值设为 1，避免未传值时出错
    },
    initialCols: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      hoverRow: 0,
      hoverCol: 0,
      selectedRow: 0,
      selectedCol: 0,
      isHovering: false
    };
  },
  computed: {
    selectedRows() {
      return this.selectedRow || 1;
    },
    selectedCols() {
      return this.selectedCol || 1;
    }
  },
  created() {
    // 初始化时根据 props 设置选中状态
    this.selectedRow = this.initialRows;
    this.selectedCol = this.initialCols;
  },
  methods: {
    handleMouseOver(row, col) {
      this.isHovering = true;
      this.hoverRow = row;
      this.hoverCol = col;
    },
    handleMouseLeave() {
      this.isHovering = false;
    },
    handleClick(row, col) {
      this.selectedRow = row;
      this.selectedCol = col;
      this.$emit('update-selection', {
        rows: this.selectedRows,
        cols: this.selectedCols
      });
    },
    isHovered(row, col) {
      return this.isHovering && row <= this.hoverRow && col <= this.hoverCol;
    },
    isSelected(row, col) {
      return this.selectedRow && this.selectedCol && row <= this.selectedRow && col <= this.selectedCol;
    }
  }
};
</script>

<style scoped>
.grid-selector {
  margin: 10px 0;
}

.grid-container {
  display: inline-block;
  border: 1px solid #dcdcdc;
}

.grid-row {
  display: flex;
}

.grid-cell {
  width: 20px;
  height: 20px;
  border: 1px solid #dcdcdc;
  background-color: #fff;
  cursor: pointer;
  transition: background-color 0.2s;
}

.grid-cell.hovered {
  background-color: #e6f7ff;
}

.grid-cell.selected {
  background-color: #409EFF;
}

.selection-info {
  margin-top: 10px;
  color: #606266;
}
</style>